package permission

import (
	"github.com/ifnk/micro-blog/internal/pkg/dbcontext"
	"github.com/ifnk/micro-blog/internal/pkg/log"
	v12 "github.com/ifnk/micro-blog/protobuf/permission_pb"
)

func NewRepository(logger *log.Logger, db *dbcontext.GormDB) Repository {
	return &repository{
		logger: logger,
		db:     db,
	}
}

type Repository interface {
	Get(id uint64) (*v12.UserORM, error)
	GetByUsername(username string) (*v12.UserORM, error)
	Create(user *v12.UserORM) error
	Update(user *v12.UserORM) error
	Delete(id uint64) error
	ExistByName(name string) (bool, error)
}
type repository struct {
	logger *log.Logger
	db     *dbcontext.GormDB
}

func (r repository) ExistByName(name string) (bool, error) {
	var exists bool
	err := r.db.Model(v12.User{}).
		Select("count(*) > 0").
		Where("username = ?", name).
		Find(&exists).
		Error
	return exists, err
}

func (r repository) GetByUsername(username string) (*v12.UserORM, error) {
	user := &v12.UserORM{}
	err := r.db.Where("username = ?", username).First(user).Error
	return user, err
}

func (r repository) Get(id uint64) (*v12.UserORM, error) {
	entity := &v12.UserORM{}
	err := r.db.First(entity, id).Error
	r.logger.Infof("entity -> %+v", entity)
	return entity, err
}

func (r repository) Create(user *v12.UserORM) error {
	return r.db.Create(user).Error
}

func (r repository) Update(user *v12.UserORM) error {
	return r.db.Save(user).Error
}

func (r repository) Delete(id uint64) error {
	// 删除有问题，后面 在修改
	return r.db.Delete(&v12.UserORM{}, id).Error
}
